/*
* @Author: xiaosihan
* @Date: 2024-07-11 10:22:49
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-08-02 00:29:20
*/
import express from "express";
import { ValidationChain, body, validationResult } from "express-validator";
import { get, isEmpty } from "lodash";
import fs from "fs";
import path from "path";

// 服务基类
export default class ServiceBase {

    constructor() {
  
    }

    // 提取post get参数
    getParame(req: express.Request) {
        return { ...(get(req, ['user'] || {})), ...(get(req, ['adminUser'] || {})), ...req.query, ...req.body };
    }

    // 判断是否登录
    isLogin(req: express.Request) {
        return !isEmpty(get(req, ['user']));
    }

    // 判断是否管理员
    isAdmin(req: express.Request) {
        return !isEmpty(get(req, ['adminUser']));
    }

    body = body;

    // parallel processing 并行处理
    // 暴露一个函数，函数接收验证规则，返回一个函数
    validate(validations: Array<ValidationChain>) {
        return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
            await Promise.all(validations.map((validation) => validation.run(req)));

            const errors = validationResult(req);
            if (errors.isEmpty()) {
                return next();
            }

            next({
                message: errors.array()[0].msg,
                code: 500
            })

        };
    }

    // 递归读取文件
    async walkDir(directory: string, callback: Function) {
        return new Promise<void>((resolve, reject) => {
            fs.readdir(directory, async (err, files) => {

                if (err) return console.error(err);

                for (let file of files) {
                    const fullPath = path.join(directory, file);

                    await new Promise<void>((resolve2, reject) => {
                        fs.stat(fullPath, (err, stats) => {
                            if (err) return console.error(err);

                            if (stats.isDirectory()) {
                                // this.walkDir(fullPath, callback);
                                resolve2();
                            } else if (stats.isFile()) {
                                callback(fullPath);
                                resolve2();
                            }
                        });
                    });
                }
                resolve();
            });
        });
    }

    // 获取文件名的后缀
    getSuffix(filename: string) {
        const match = filename.match(/\.([^\.]+)$/);
        return match ? match[1].toLowerCase() : '';
    }

    // 返回成功的状态
    success(res: express.Response, data: any = undefined, message = "成功") {
        res.send({
            status: "success",
            code: 200,
            message,
            data
        });
    }

    //返回失败的状态
    error(res: express.Response, message = "失败") {
        res.send({
            status: "error",
            code: 401,
            message
        });
    }

    // 查询
    query(sqlString: string): any {
        // return sql.query(sqlString, values);
    }
}